package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.gap.cache.redis.RedisCache;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.vo.OperationLogVO;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.dto.LogVO;
import com.mingqijia.gassafety.shared.enums.YesNoEnum;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.CompareUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.BeanConvertUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.webserver.request.*;
import com.mingqijia.gassafety.webserver.response.*;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkUserListResponse;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.webserver.utils.LogRecordAspect;
import com.mingqijia.gassafety.webserver.utils.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.APPEAL_STATUS_3;
import static com.mingqijia.gassafety.shared.constant.Constants.IS_DELETED_FALSE;
import static com.mingqijia.gassafety.shared.constant.TableConst.dtu;
import static com.mingqijia.gassafety.webserver.constant.DeviceConstant.*;

/**
 * <p>
 * 服务信息表 服务实现类
 * </p>
 *
 * @author mby
 * @since 2024-01-12
 */
@Service
@Slf4j
public class ConsumerServiceInfoServiceImpl extends ServiceImpl<ConsumerServiceInfoMapper, ConsumerServiceInfo> implements ConsumerServiceInfoService {

    @Autowired
    private CompareUtil compareUtil;
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    OperationLogService operationLogService;
    @Autowired
    ConsumerServiceInfoMapper consumerServiceInfoMapper;
    @Autowired
    ConsumerService consumerService;
    @Autowired
    AppealLogService appealLogService;
    @Autowired
    RedisCache redisCache;
    @Autowired
    ConsoleSkFeignClient consoleSkFeignClient;

    @Autowired
    private ServicePkgRecordService servicePkgRecordService;

    @Override
    @Transactional
    public String editConsumerServiceInfo(SaveConsumerServiceInfoRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        QueryWrapper<ConsumerServiceInfo> queryOldWrapper = new QueryWrapper<>();
        queryOldWrapper.lambda().eq(ConsumerServiceInfo::getId, request.getId())
                .eq(ConsumerServiceInfo::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(ConsumerServiceInfo::getSpId, spId);
        ConsumerServiceInfo consumerServiceInfoOld = this.getOne(queryOldWrapper);

        //比较客户信息发生的变化
        //操作日志log
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        String after = JSONObject.toJSONString(request);
        String before = JSONObject.toJSONString(consumerServiceInfoOld);
        logVO.setOperationBefore(before);
        logVO.setOperationAfter(after);

        ConsumerServiceInfo consumerServiceInfo = new ConsumerServiceInfo();
        BeanUtils.copyProperties(consumerServiceInfoOld, consumerServiceInfo);
        consumerServiceInfo.setServiceInfo(request.getServiceInfo());

        consumerServiceInfo.setStartDate(request.getStartDate());
        consumerServiceInfo.setEndDate(request.getEndDate());
        consumerServiceInfo.setRemark(request.getRemark());
        // 修改安装时间时服务信息不再更新
        consumerServiceInfo.setIsUpdate(1);
        Long today = DateUtils.today().getTime();
        Long endDate = request.getEndDate().getTime();
        if (today < endDate && endDate - today > 30*24*60*60*1000L) {
            redisCache.deleteObject(Constants.WARNING_SERVICE_PERIOD_RUNNING + ":" + request.getImei());
            consumerServiceInfo.setIsSend(0);
        }
        //比较哪些字段发生改变
        Field[] fields = consumerServiceInfoOld.getClass().getDeclaredFields();
        Map<String, String> compare = compareUtil.compare(fields, consumerServiceInfo, consumerServiceInfoOld);
        //服务信息
        if (StringUtil.isNotEmpty(compare.get("serviceInfo"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_38.getCode());
        }
        //修改服务开始日期
        if (StringUtil.isNotEmpty(compare.get("startDate"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_39.getCode());
        }
        //修改服务结束日期
        if (StringUtil.isNotEmpty(compare.get("endDate"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_40.getCode());
        }
        //修改备注
        if (StringUtil.isNotEmpty(compare.get("remark"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_41.getCode());
        }

        if (CollectionUtil.isNotEmpty(logCodeList)) {
            logVO.setCodeList(logCodeList);
            logVO.setTableName(TableConst.t_gss_consumer_service_info.name());
            logVO.setTableKey(request.getId().toString());
            operationLogService.insertLog(logVO);
        }

        boolean flag = this.updateById(consumerServiceInfo);

        LambdaUpdateWrapper<Consumer> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(Consumer::getSpId, spId).eq(Consumer::getId, consumerServiceInfoOld.getConsumerId())
            .eq(Consumer::getIsDeleted, IS_DELETED_FALSE)
            .set(Consumer::getServiceCreator, ApplicationUtils.getWorkingUser().getUsername())
            .set(Consumer::getServiceCreatorName,ApplicationUtils.getWorkingUser().getName())
            .set(Consumer::getServiceUpdateTime,new Date());
        consumerService.update(lqw);

        ConsumerServiceInfo newOne = this.getById(consumerServiceInfo.getId());
        //企业级操作日志
        LogVO vo = new LogVO();
        vo.setDetail(LogUtil.compareEntity(newOne, consumerServiceInfoOld, ConsumerServiceInfo.class));
        LogRecordAspect.threadLocal.set(vo);

        if (!flag) {
            throw new BizException("更新客户信息失败");
        }
        return "";
    }

    @Override
    @Transactional
    public void addConsumerServiceInfo(Integer isUpdate, String imei, Consumer consumer) {
        LambdaQueryWrapper<Dtu> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Dtu::getIMEI,imei).eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);
        Dtu dtu = equipmentService.getOne(queryWrapper);
        ConsumerServiceInfo service = new ConsumerServiceInfo();
        service.setId(null);
        service.setConsumerId(dtu.getConsumerId());
        service.setIndustryType(consumer.getIndustryType());
        service.setImei(dtu.getIMEI());
        try {
            service.setStartDate(DateUtils.toDate(dtu.getInstallDate()));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        try {
            if (consumer != null && consumer.getPkgId() != null && consumer.getPkgId() > 0) {
                LambdaQueryWrapper<ServicePkgRecord> recordLambdaQueryWrapper = new LambdaQueryWrapper();
                recordLambdaQueryWrapper.eq(ServicePkgRecord::getId, consumer.getPkgId())
                        .gt(ServicePkgRecord::getPgkCycle, 0)
                        .eq(ServicePkgRecord::getIsDeleted, Constants.IS_DELETED_FALSE);
                ServicePkgRecord servicePkgRecord = servicePkgRecordService.getOne(recordLambdaQueryWrapper);
                if (servicePkgRecord != null && StringUtils.isNotEmpty(servicePkgRecord.getPgkCycleUnit()) && servicePkgRecord.getPgkCycle() != null) {
                    //周期单位
                    if ("年".equals(servicePkgRecord.getPgkCycleUnit())) {
                        service.setEndDate(DateUtils.getDiffYearDate(DateUtils.toDate(dtu.getInstallDate()), servicePkgRecord.getPgkCycle()));
                    } else {
                        service.setEndDate(DateUtils.getDiffMonData(DateUtils.toDate(dtu.getInstallDate()), servicePkgRecord.getPgkCycle()));
                    }
                } else {
                    if (EquipmentType.HOME_GAS_DETECTOR.getCode().equals(dtu.getEquipmentType())){
                        service.setEndDate(DateUtils.getDiffYearDate(DateUtils.toDate(dtu.getInstallDate()), 5));
                    } else {
                        // 工商业报警器
                        service.setEndDate(DateUtils.getDiffYearDate(DateUtils.toDate(dtu.getInstallDate()), 3));
                    }
                }
            } else {
                if (EquipmentType.HOME_GAS_DETECTOR.getCode().equals(dtu.getEquipmentType())){
                    service.setEndDate(DateUtils.getDiffYearDate(DateUtils.toDate(dtu.getInstallDate()), 5));
                } else {
                    // 工商业报警器
                    service.setEndDate(DateUtils.getDiffYearDate(DateUtils.toDate(dtu.getInstallDate()), 3));
                }
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        service.setRemark(new StringBuilder().append("设备号：").append(dtu.getIMEI())
                .append("安装日期：").append(dtu.getInstallDate()).append("当前状态：关联").toString());
        service.setIsDeleted(YesNoEnum.N.isFlag());
        service.setCreatedAt(new Date());
        service.setUpdatedAt(service.getCreatedAt());
        service.setSpId(dtu.getSpId());
        service.setIsUpdate(isUpdate == null ? 0 : isUpdate);
        service.setIsSend(0);
        consumerServiceInfoMapper.insert(service);
    }

    @Override
    @Transactional
    public void addDeleteConsumerServiceInfo(Integer isUpdate, String imei, String industryType) {
        LambdaQueryWrapper<Dtu> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Dtu::getIMEI,imei).eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);
        Dtu dtu = equipmentService.getOne(queryWrapper);
        if(dtu == null) {
            throw new RuntimeException("设备信息不存在");
        }
        if(dtu.getInstallTime() == null) {
            dtu.setInstallTime(new Date());
        }
        if(StringUtils.isEmpty(dtu.getInstallDate())) {
            dtu.setInstallDate(DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN));
        }
        
        LambdaUpdateWrapper<ConsumerServiceInfo> seleteWrapper = new LambdaUpdateWrapper<>();
        seleteWrapper.eq(ConsumerServiceInfo::getImei, imei)
                .set(ConsumerServiceInfo::getIsDeleted, 0);
        List<ConsumerServiceInfo> serviceInfos = consumerServiceInfoMapper.selectList(seleteWrapper);
        if (CollectionUtils.isNotEmpty(serviceInfos)) {
            LambdaUpdateWrapper<ConsumerServiceInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ConsumerServiceInfo::getImei, imei)
                    .set(ConsumerServiceInfo::getIsDeleted, YesNoEnum.Y.isFlag());
            this.update(updateWrapper);
            // 删除缓存
            redisCache.deleteObject(Constants.WARNING_SERVICE_PERIOD_RUNNING + ":" + imei);
        }
        ConsumerServiceInfo service = new ConsumerServiceInfo();
        service.setId(null);
        service.setConsumerId(dtu.getConsumerId());
        service.setIndustryType(industryType);
        service.setImei(dtu.getIMEI());
        try {
            service.setStartDate(DateUtils.toDate(dtu.getInstallDate()));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        try {
            if (EquipmentType.HOME_GAS_DETECTOR.getCode().equals(dtu.getEquipmentType())){
                service.setEndDate(DateUtils.getDiffYearDate(DateUtils.toDate(dtu.getInstallDate()), 5));
            } else {
                // 工商业报警器
                service.setEndDate(DateUtils.getDiffYearDate(DateUtils.toDate(dtu.getInstallDate()), 3));
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        service.setRemark(new StringBuilder().append("设备号：").append(dtu.getIMEI())
                .append("安装日期：").append(dtu.getInstallDate()).append("当前状态：关联").toString());
        service.setIsDeleted(YesNoEnum.N.isFlag());
        service.setCreatedAt(new Date());
        service.setUpdatedAt(service.getCreatedAt());
        service.setSpId(dtu.getSpId());
        service.setIsUpdate(isUpdate == null ? 0 : isUpdate);
        service.setIsSend(0);
        consumerServiceInfoMapper.insert(service);
    }

    @Override
    @Transactional
    public void addConsumerServiceInfo(String imei, String oldImei, String industryType) {
        log.info("unbindEquipment-addConsumerServiceInfo:imei:{}, oldImei:{},industryType:{}",imei, oldImei, industryType);
        LambdaQueryWrapper<Dtu> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Dtu::getIMEI,imei).eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);
        Dtu dtu = equipmentService.getOne(queryWrapper);
        LambdaQueryWrapper<ConsumerServiceInfo> serviceInfoQueryWrapper = new LambdaQueryWrapper();
        serviceInfoQueryWrapper.eq(ConsumerServiceInfo::getImei,oldImei).orderByAsc(ConsumerServiceInfo::getUpdatedAt);;
        ConsumerServiceInfo serviceInfo = null ;
        List<ConsumerServiceInfo> serviceInfoList = this.list(serviceInfoQueryWrapper);
        if (CollectionUtils.isNotEmpty(serviceInfoList)) {
            serviceInfo = serviceInfoList.get(0);
        } else {
            log.info("unbindEquipment-addConsumerServiceInfo:oldImei:{}, 老服务信息不存在",oldImei);
            return ;
        }
        ConsumerServiceInfo service = new ConsumerServiceInfo();
        service.setId(null);
        service.setConsumerId(serviceInfo.getConsumerId());
        service.setIndustryType(industryType);
        service.setImei(dtu.getIMEI());
        service.setStartDate(serviceInfo.getStartDate());
        service.setEndDate(serviceInfo.getEndDate());
        service.setRemark(new StringBuilder().append("设备号：").append(dtu.getIMEI())
                .append("安装日期：").append(dtu.getInstallDate()).append("当前状态：关联").toString());
        service.setIsDeleted(YesNoEnum.N.isFlag());
        service.setCreatedAt(new Date());
        service.setUpdatedAt(service.getCreatedAt());
        service.setSpId(dtu.getSpId());
        service.setIsUpdate(1);
        service.setIsSend(0);
        consumerServiceInfoMapper.insert(service);
    }

    @Override
    @Transactional
    public void deleteConsumerServiceInfo(String imei) {
        LambdaUpdateWrapper<ConsumerServiceInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ConsumerServiceInfo::getImei, imei)
                .set(ConsumerServiceInfo::getIsDeleted, YesNoEnum.Y.isFlag());
        this.update(updateWrapper);
        // 删除缓存
        redisCache.deleteObject(Constants.WARNING_SERVICE_PERIOD_RUNNING + ":" + imei);
    }

    @Override
    public PageUtil<ConsumerServiceInfoResponse> queryConsumerServiceInfoList(ConsumerServiceInfoListRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        if (!StringUtils.isEmpty(request.getSpId())) {
            spId = request.getSpId();
        }
        Page<ConsumerServiceInfo> page = null;

        QueryWrapper<ConsumerServiceInfo> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().eq(request.getConsumerId() != null, ConsumerServiceInfo::getConsumerId, request.getConsumerId())
                .eq(ConsumerServiceInfo::getSpId, spId)
                .eq(ConsumerServiceInfo::getConsumerId, request.getConsumerId())
                .eq(ConsumerServiceInfo::getIsDeleted, IS_DELETED_0)
                .orderByDesc(ConsumerServiceInfo::getUpdatedAt);
        page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<ConsumerServiceInfo> consumerServiceInfoList = this.list(queryWrapper);
        List<ConsumerServiceInfoResponse> list = BeanConvertUtils.convertListTo(consumerServiceInfoList, ConsumerServiceInfoResponse::new);
        List<String> imeis = consumerServiceInfoList.stream()
                .map(ConsumerServiceInfo::getImei).distinct().collect(Collectors.toList());
        Long today = DateUtils.today().getTime();
        Map<String, String> dtuInstallDateMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(consumerServiceInfoList)) {
            QueryWrapper<Dtu> dtuWrapper = new QueryWrapper<>();
            dtuWrapper.lambda().eq(Dtu::getIsDeleted, IS_DELETED_0)
                .eq(Dtu::getSpId, spId)
                .eq(Dtu::getConsumerId, request.getConsumerId())
                .in(Dtu::getIMEI, imeis);
            List<Dtu> dtuList = equipmentService.list(dtuWrapper);
            if (CollectionUtils.isNotEmpty(dtuList)) {
                dtuList.stream().forEach(x -> {
                    dtuInstallDateMap.put(x.getIMEI(), x.getInstallDate());
                });
            }
        }
        LambdaQueryWrapper<Consumer> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Consumer::getId, request.getConsumerId()).eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
        Consumer consumer = consumerService.getOne(wrapper);
        ServicePkgRecordListResp recordListResp = new ServicePkgRecordListResp();
        if (consumer != null && consumer.getPkgId() != null && consumer.getPkgId() > 0) {
            recordListResp = servicePkgRecordService.detail(consumer.getPkgId());
        }

        for (ConsumerServiceInfoResponse res : list) {
            if (today == res.getEndDate().getTime()) {
                res.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_4.getCode());
            }  else if (today < res.getEndDate().getTime()) {
                if (res.getEndDate().getTime() - today <= 7*24*60*60*1000) {
                    res.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_3.getCode());
                } else if (res.getEndDate().getTime() - today <= 30*24*60*60*1000L) {
                    res.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_2.getCode());
                } else {
                    res.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_1.getCode());
                }
            } else if (today > res.getEndDate().getTime()) {
                if (today - res.getEndDate().getTime() <= 7*24*60*60*1000) {
                    res.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_5.getCode());
                } else {
                    res.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_6.getCode());
                }
            }
            res.setServiceStatusName(ConsumerServiceStatusEnum.getConsumerServiceStatusEnum(res.getServiceStatus()).getName());
            res.setInstallDate(dtuInstallDateMap.get(res.getImei()) == null ? "" : dtuInstallDateMap.get(res.getImei()));
            if (recordListResp != null) {
                res.setPkgId(recordListResp.getId());
                res.setPkgName(recordListResp.getPgkName());
                res.setDataSource(recordListResp.getDataSource());
                res.setDataSourceName(recordListResp.getDataSourceName());
                res.setPgkCycle(recordListResp.getPgkCycle());
                res.setPgkCycleUnit(recordListResp.getPgkCycleUnit());
            }
        }
        PageUtil<ConsumerServiceInfoResponse> pageUtil = new PageUtil<>();
        pageUtil.setPage(request.getPage());
        pageUtil.setPageSize(request.getPageSize());
        pageUtil.setTotal(page.getTotal());
        pageUtil.setList(list);
        return pageUtil;
    }

    @Override
    public LatestConsumerServiceSummaryResponse queryConsumerServiceInfoTab() {
        LatestConsumerServiceSummaryResponse resp = new LatestConsumerServiceSummaryResponse();
        String spId = ApplicationUtils.getWorkingSpId();

        QueryWrapper<Dtu> dtuWrapper = new QueryWrapper<>();
        dtuWrapper.lambda().eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Dtu::getSpId, spId);
        List<Dtu> equipmentList = equipmentService.list(dtuWrapper);

        QueryWrapper<ConsumerServiceInfo> consumerServiceInfoWrapper = new QueryWrapper<>();
        consumerServiceInfoWrapper.lambda().eq(ConsumerServiceInfo::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(ConsumerServiceInfo::getSpId, spId);
        List<ConsumerServiceInfo> consumerServiceInfoList = this.list(consumerServiceInfoWrapper);
        Map<String, ConsumerServiceInfo> consumerServiceInfoMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(consumerServiceInfoList)) {
            consumerServiceInfoList.stream().forEach(item -> {
                consumerServiceInfoMap.put(item.getImei(), item);
            });
        }
        Long today = DateUtils.today().getTime();
        if (CollectionUtils.isNotEmpty(equipmentList) && CollectionUtils.isNotEmpty(consumerServiceInfoList)) {
            equipmentList.stream().forEach(item -> {
                if (consumerServiceInfoMap.get(item.getIMEI()) != null) {
                    Long endDate = consumerServiceInfoMap.get(item.getIMEI()).getEndDate().getTime();
                    if (today == endDate) {
                        resp.setPeriodCount(resp.getPeriodCount() + 1);
                    }  else if (today < endDate) {
                        if (endDate - today<= 7*24*60*60*1000) {
                            resp.setUnexpiredLessSevenCount(resp.getUnexpiredLessSevenCount() + 1);
                        } else if (endDate - today <= 30*24*60*60*1000L) {
                            resp.setUnexpiredLessThirtyCount(resp.getUnexpiredLessThirtyCount() + 1);
                        } else {
                            resp.setNormalCount(resp.getNormalCount() + 1);
                        }
                    } else if (today > endDate) {
                        if (today - endDate <= 7*24*60*60*1000) {
                            resp.setExpiredLessSevenCount(resp.getExpiredLessSevenCount() + 1);
                        } else {
                            resp.setExpiredMoreSevenCount(resp.getExpiredMoreSevenCount() + 1);
                        }
                    }
                }
//                else {
//                    resp.setNormalCount(resp.getNormalCount() + 1);
//                }
            });
        }

        resp.setAllCount(resp.getNormalCount() + resp.getUnexpiredLessThirtyCount() + resp.getUnexpiredLessSevenCount() +
                resp.getPeriodCount() + resp.getExpiredLessSevenCount() + resp.getExpiredMoreSevenCount());

        return resp;
    }

    @Override
    public Map<Integer, LatestConsumerServiceSummaryResponse> queryConsumerServiceInfoMap(List<Integer> consumerIds) {
        Map<Integer, LatestConsumerServiceSummaryResponse> map =new HashMap<>();
        QueryWrapper<ConsumerServiceInfo> consumerServiceInfoWrapper = new QueryWrapper<>();
        consumerServiceInfoWrapper.lambda().eq(ConsumerServiceInfo::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(ConsumerServiceInfo::getConsumerId, consumerIds);
        List<ConsumerServiceInfo> consumerServiceInfoList = this.list(consumerServiceInfoWrapper);
        Map<String, ConsumerServiceInfo> consumerServiceInfoMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(consumerServiceInfoList)) {
            consumerServiceInfoList.stream().forEach(item -> {
                consumerServiceInfoMap.put(item.getImei(), item);
            });
        }
        Long today = DateUtils.today().getTime();
        if (CollectionUtils.isNotEmpty(consumerServiceInfoList)) {
            consumerServiceInfoList.stream().forEach(item -> {
                if (map.get(item.getConsumerId()) == null) {
                    map.put(item.getConsumerId(), new LatestConsumerServiceSummaryResponse());
                }
                if (today == item.getEndDate().getTime()) {
                    map.get(item.getConsumerId()).setPeriodCount(map.get(item.getConsumerId()).getPeriodCount() + 1);
                }  else if (today < item.getEndDate().getTime()) {
                    if (item.getEndDate().getTime() - today <= 7*24*60*60*1000) {
                        map.get(item.getConsumerId()).setUnexpiredLessSevenCount(map.get(item.getConsumerId()).getUnexpiredLessSevenCount() + 1);
                    } else if (item.getEndDate().getTime() - today <= 30*24*60*60*1000L) {
                        map.get(item.getConsumerId()).setUnexpiredLessThirtyCount(map.get(item.getConsumerId()).getUnexpiredLessThirtyCount() + 1);
                    } else {
                        map.get(item.getConsumerId()).setNormalCount(map.get(item.getConsumerId()).getNormalCount() + 1);
                    }
                } else if (today > item.getEndDate().getTime()) {
                    if (today - item.getEndDate().getTime() <= 7*24*60*60*1000) {
                        map.get(item.getConsumerId()).setExpiredLessSevenCount(map.get(item.getConsumerId()).getExpiredLessSevenCount() + 1);
                    } else {
                        map.get(item.getConsumerId()).setExpiredMoreSevenCount(map.get(item.getConsumerId()).getExpiredMoreSevenCount() + 1);
                    }
                }

            });
        }

        return map;
    }

    @Override
    public String queryBindDevice(ConsumerunBindDeviceRequest request) {
        log.info("查询家庭成员" + request.getImei());
        ConsoleSkUserListResponse consoleSkUserListResponse = consoleSkFeignClient
                .alarmSOSUserList(request.getImei());
        log.info(new StringBuilder().append("需要给").append(request.getImei()).append("的家庭成员发送信息，信息如下").append(consoleSkUserListResponse).toString());;
        if (consoleSkUserListResponse != null && consoleSkUserListResponse.getData() != null
                && CollectionUtil.isNotEmpty(consoleSkUserListResponse.getData().getUserList())) {
            return "该设备被C端用户绑定，是否确认解除绑定，解除后，C端用户将看不到此设备，请确认！";
        }
        return "";
    }

    @Override
    public Boolean checkConsumerImeiServiceDate(String spId,Integer consumerId,String imei) {
        String tImei = imei;
        if (imei.contains("-")){
            tImei = tImei.split("-")[0];
        }
        log.info("checkConsumerImeiServiceDate spId:{},imei:{},tImei:{},consumerId:{}",spId,imei,tImei,consumerId);
        LambdaQueryWrapper<ConsumerServiceInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ConsumerServiceInfo::getSpId, spId);
        queryWrapper.eq(ConsumerServiceInfo::getConsumerId, consumerId);
        queryWrapper.eq(ConsumerServiceInfo::getImei, tImei);
        queryWrapper.eq(ConsumerServiceInfo::getIsDeleted, false);
        List<ConsumerServiceInfo> consumerServiceInfos = this.baseMapper.selectList(queryWrapper);
        if (null == consumerServiceInfos || consumerServiceInfos.isEmpty()) {
            return false;
        }
        log.info("checkConsumerImeiServiceDate consumerServiceInfos:{}",JSONObject.toJSONString(consumerServiceInfos));
        Date startDate = consumerServiceInfos.get(0).getStartDate();
        Date endDate = consumerServiceInfos.get(0).getEndDate();
        Date currDate = new Date();
        return startDate.getTime() <= currDate.getTime() && endDate.getTime() >= currDate.getTime();
    }
}
